package com.ibo.htlivecamera.util;

import android.os.AsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/8/5.
 */

public class Downloader extends AsyncTask<String, String, String> {
    private final File path;

    private boolean isCancel = false;
    private DownloadListener downloadListener;

    public Downloader(File path, DownloadListener downloadListener) {
        this.downloadListener = downloadListener;
        if (!path.getParentFile().exists()) {
            path.getParentFile().mkdirs();
        }
        this.path = path;
    }

    public void cancelDownload() {
        isCancel = true;
    }

    @Override
    protected String doInBackground(String... strings) {
        String fileURL = strings[0];

        /* 所下载文件的URL */
        try {
            URL url = new URL(fileURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            /* URL属性设置 */
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Encoding", "identity");//才能获取到getContentLength()的值

            /* URL建立连接 */
            conn.connect();
            //判断服务端正常的反馈是否已经到达了 客户端
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return null;
            }

            /* 下载文件的大小 */
            int fileOfLength = conn.getContentLength();
            /* 每次下载的大小与总下载的大小 */
            long totalLength = 0;
            int length = 0;
            /* 输入流 */
            InputStream in = conn.getInputStream();
            /* 输出流 */
            FileOutputStream out = new FileOutputStream(new File(path.getParent(), path.getName()));
            /* 缓存模式，下载文件 */
            byte[] buff = new byte[1024 * 1024];
            while ((length = in.read(buff)) > 0) {
                if (isCancel) {
                    return "";
                }
                conn.getContentLength();
                totalLength += length;

                String str1;
                if (fileOfLength <= 0) {
                    str1 = "" + totalLength;
                } else {
                    str1 = "" + (totalLength * 100 / fileOfLength);
                }
                publishProgress(str1);
                out.write(buff, 0, length);
            }
            /* 关闭输入输出流 */
            in.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            return null;
        }
        return fileURL;
    }

    public interface DownloadListener {
        void onProgressUpdate(int progress);

        void downloadCompleted(boolean isSuccess);

        void downloadCancel();
    }

    private String lastProgress = "";

    protected void onProgressUpdate(String... progress) {
        if (downloadListener == null) return;
        if (lastProgress.equals(progress[0])) return;
        lastProgress = progress[0];

        downloadListener.onProgressUpdate(Integer.parseInt(lastProgress));
    }

    @Override
    protected void onPostExecute(String unused) {
        if (downloadListener == null) return;

        if (unused == null) {
            downloadListener.downloadCompleted(false);
        } else if (unused.equals("")) {
            downloadListener.downloadCancel();
        } else {
            downloadListener.downloadCompleted(true);
        }
    }
}
